package com.ktc.user.controller;

import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.Claims;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ktc.user.pojo.Admin;
import com.ktc.user.service.AdminService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;

/**
 * @author admin
 * @Description 管理员 控制器层
 * @date 2021-04-15 11:06:37
 */
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;


    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;

    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.OK, true, "查询成功", adminService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.OK, true, "查询成功", adminService.findById(id));
    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Admin> pageList = adminService.findSearch(searchMap, page, size);
        return new Result(StatusCode.OK, true, "查询成功", new PageResult<Admin>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.OK, true, "查询成功", adminService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param admin
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Admin admin) {
        adminService.add(admin);
        return new Result(StatusCode.OK, true, "增加成功");
    }

    /**
     * 修改
     *
     * @param admin
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody Admin admin, @PathVariable String id) {
        admin.setId(id);
        adminService.update(admin);
        return new Result(StatusCode.OK, true, "修改成功");
    }


    @Autowired
    private Environment env;

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {

        // 有没有登录
        // 取请求头的auth  dfbz_token
        /*String auth = request.getHeader("auth");

        if (auth == null) {
            return new Result(StatusCode.ACCESS_ERROR, false, "请先认证");
        }

        String prefix = env.getProperty("jwt.config.prefix");

        if (!auth.startsWith(prefix)) {
            return new Result(StatusCode.ACCESS_ERROR, false, "认证不合法");
        }

        String token = auth.substring(prefix.length());
        Claims claims = jwtUtil.parseJWT(token);

        if (!claims.get("role").equals("admin")) {
            return new Result(StatusCode.ACCESS_ERROR, false, "权限不足！");
        }*/

        Claims user_claims = (Claims) request.getAttribute("admin_claims");

        if (user_claims == null) {
            return new Result(StatusCode.ACCESS_ERROR, false, "请先认证");
        }

        adminService.deleteById(id);
        return new Result(StatusCode.OK, true, "删除成功");
    }

    /**
     * 管理员登录
     *
     * @param admin
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody Admin admin) {

        Admin dbAdmin = adminService.findByLoginname(admin.getLoginname());
        if (dbAdmin == null || !encoder.matches(admin.getPassword(), dbAdmin.getPassword())) {
            return new Result(StatusCode.OK, true, "用户名或密码错误");
        }

        String token = jwtUtil.createJWT(dbAdmin.getId(), dbAdmin.getLoginname(), "admin");

        Map returnMap = new HashMap();
        returnMap.put("token", token);
        returnMap.put("loginname", dbAdmin.getLoginname());

        return new Result(StatusCode.OK, true, "登录成功", returnMap);
    }

}
